package com.cyou.nad.tag.table.pagebar;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.cyou.nad.filter.RespCharFilterValidator;

/**
 * 
 * @author lzm 
 */
public abstract class AbstractPageBar implements PageBar {

	public AbstractPageBar() {
		super();
	}

	@SuppressWarnings("unchecked")
	protected StringBuffer builderSearchForm(HttpServletRequest req, String formId, String formAction, int totalRow,
			int pageSize) {
		/**
		 * 处理在formAction中的参数，比如index.do?a=1 中的a
		 */
		StringBuffer formActionBuffer =  new StringBuffer(formAction);
		Map<String,String> keymap = new HashMap<String,String>();	
		int index = formActionBuffer.indexOf("?");
		if(index!=-1){
			formActionBuffer = new StringBuffer(formActionBuffer.substring(index+1));
			String str = formActionBuffer.toString();
			String[] strArr = str.split("&");
			for(int i = 0; i< strArr.length;i++){
				String[] subArr = strArr[i].split("=");
				keymap.put(subArr[0].trim(),subArr[0].trim());
			}
		}
		StringBuffer sb = new StringBuffer("<form action='").append(formAction)
			.append("' id='").append(formId).append("' method='get'>");
		for (Enumeration<String> enu = req.getParameterNames(); enu.hasMoreElements();) {
			String key = enu.nextElement();
			String[] params = req.getParameterValues(key);
			if (params == null || params.length < 1) {
				;
			} else {
				if (key.equals(PageBar.REQUEST_PARAMETER_TOTALROWS)) {
					continue;
				}
				if (key.equals(PageBar.REQUEST_PARAMETER_PAGE)) {
					continue;
				}
				if (key.equals(PageBar.REQUEST_PARAMETER_PAGE_SIZE)) {
					continue;
				}
				if(keymap.containsKey(key)){
					continue;
				}

				buildParam(sb, key, params);
			}
		}
		sb.append("<input type='hidden' name='").append(REQUEST_PARAMETER_TOTALROWS).append("'").append("  value='")
				.append(totalRow).append("'/>");
		sb.append("<input type='hidden' name='").append(REQUEST_PARAMETER_PAGE_SIZE).append("'").append("  value='")
				.append(pageSize).append("'/>");
		sb.append("<input type='hidden' id='" + REQUEST_PARAMETER_PAGE + formId + "' name='").append(
				REQUEST_PARAMETER_PAGE).append("'").append("  value=''/>");
		sb.append("</form>");
		return sb;
	}

	private StringBuffer buildParam(StringBuffer sb, String key, String[] params) {
		for (String string : params) {
			sb.append("<input type='hidden' name='").append(RespCharFilterValidator.filter(key)).append("'").append("  value='").append(RespCharFilterValidator.filter(string)).append("'/>");
		}
		return sb;
	}

}